;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Corruption.BuyBackWarn", [])
        .controller("BuyBackWarnCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService","$stateParams", function ($scope, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService,$stateParams) {
            $scope.handleMultiInput = function (e) {
                $scope.condition.materialsNos = UserContextService.MultiInput(e.target.value);
            };

            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.toolbarConfig = {
                showColConfig: false
            };


            $scope.condition = {};
            $scope.dataList = [];
            $scope.tableConfig = {
                fixedWidth: 100,
                scrollWidth: 1400,
                tableCol: [
                    {
                        name: "回购订单",
                        dataField: "backOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "创建人",
                        dataField: "createName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "第一步审核人",
                        dataField: "firstAuditName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "第二步审核人",
                        dataField: "secondAuditName",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "备注",
                        dataField: "warningRemark",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "创建时间",
                        dataField: "createDate",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: 'operate',
                        name: "操作",
                        width: 60,
                        isShow: true,
                        isFixed: true,
                    },
                ]
            };
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.exportParam = {
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/buyBack/exportAllWarning")
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function getDataList(curPage) {
                $scope.markInfo.allChecked = false;
                $scope.markInfo.curRow = -1;
                $scope.exportParam.sectionParam.ids = [];

                var service = "device";
                var reqUrl = "/buyBack/warningPageList";

                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }

                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: angular.copy($scope.condition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDate = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }


            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectAll = function (list, type) {
                for (var i = 0, len = list.length; i < len; i++) {
                    list[i].isChecked = angular.isUndefined(type) ? $scope.markInfo.allChecked : $scope.markInfo["allChecked" + type];
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    if (!checkAll(list)) {
                        selectAll = false;
                    } else {
                        selectAll = true;
                    }
                }
                if (angular.isDefined(type)) {
                    $scope.markInfo["allChecked" + type] = selectAll;
                } else {
                    $scope.markInfo.allChecked = selectAll;
                }
                getBillIds();
            };

            $scope.addWarning = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要生成督办单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/buyBack/warnToSup";

                    ybHttp.Post(service, reqUrl, selectedDatas.map(s => s.id)).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            function handleUpdateRemark(ids) {
                ybWidget.ShowConfirm("维护备注", [{label: '备注'}]).then(function (data) {
                    var service = "device";
                    var reqUrl = "/buyBack/remarkWarningBills";

                    var param = {
                        ids: ids,
                        remark: data[0].value,
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            }

            $scope.updateRemarkBatch = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }
                handleUpdateRemark(selectedDatas.map(s => s.id));
            };


            $scope.updateRemark = function (item) {
                handleUpdateRemark([item.id]);
            };


            $scope.activeFlag = [true, false, false, false];
            // 切换标签页
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;

                $scope.submitted = false;
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.echartsOption1 = {
                title: {
                    text: '未开票-代理商'
                },
                legend: {
                    data: ['数量']
                },
                label: {
                    show: true,
                    position: 'top',
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            rotate: 45
                        },
                        data: []
                    }
                ],
                series: [{name: '数量', type: 'bar'}],
                dataZoom: [
                    {
                        type: 'inside',
                    }
                ]
            };

            $scope.echartsCondition1 = {};
            $scope.echartsSearch1 = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }

                ybHttp.Post('device', '/reportUninvoiceWarn/reportUninvoiceWarn1Rpt', $scope.echartsCondition1).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const resT = resp.value || [];
                    $scope.echartsOption1.xAxis[0].data = resT.map(r => r.purchaseOrgName);
                    $scope.echartsOption1.series[0].data = resT.map(r => r.opNum);
                });
            };

            $scope.echartsOption2 = {
                title: {
                    text: '未开票-预警时间'
                },
                legend: {
                    data: ['数量']
                },
                label: {
                    show: true,
                    position: 'top',
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            rotate: 45
                        },
                        data: []
                    }
                ],
                series: [{name: '数量', type: 'bar'}],
                dataZoom: [
                    {
                        type: 'inside',
                    }
                ]
            };

            $scope.echartsCondition2 = {};
            $scope.echartsSearch2 = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }

                ybHttp.Post('device', '/reportUninvoiceWarn/reportUninvoiceWarn2Rpt', $scope.echartsCondition2).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const resT = resp.value || [];
                    $scope.echartsOption2.xAxis[0].data = resT.map(r => r.day);
                    $scope.echartsOption2.series[0].data = resT.map(r => r.opNum);
                });
            };
          //回购申请预警-编辑
            var btnPermissionCode = {
                buyBackWarnEdit: window.ActionCode.buyBackWarnEdit,
                buyBackWarnExport: window.ActionCode.buyBackWarnExport,
                buyBackWarnToDbd:window.ActionCode.buyBackWarnToDbd,
            };
            $scope.btnPermission = {
                buyBackWarnEdit: true,
                buyBackWarnExport: true,
                buyBackWarnToDbd: true,
            };
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }


            (function () {
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                if ($stateParams.billNo) {
					$scope.condition.id = $stateParams.billNo
					getDataList();
				}else {
					getDataList();
				}
            })();
        }])
    ;
})(window, window.angular);
